using System.Web.Mvc;
using Orchard.Localization;
using Orchard;
using Orchard.Mvc;
using System;
using Orchard.Themes;
using PmpNetwork.Services;
using Orchard.Security;

namespace PmpNetwork.Controllers {
    public class WikiController : Controller {
        private static readonly string _defaultWikiName = "index";
        private readonly IOrchardServices _services;
        private readonly IWikiArticleService _wikiService;
        private readonly IQuestionService _questionService;
        private readonly IAuthorizationService _authorizationService;

        public WikiController(IOrchardServices services,
                IWikiArticleService wikiService,
                IQuestionService questionService,
                IAuthorizationService authorizationService) 
        {
            _services = services;
            _wikiService = wikiService;
            _questionService = questionService;
            _authorizationService = authorizationService;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        [Themed]
        public ActionResult Index(string name)
        {
            string wikiName = String.IsNullOrWhiteSpace(name) ? _defaultWikiName : name.ToLower();
            var wikiPart = _wikiService.Get(name);

            if (wikiPart == null && String.Compare(wikiName, _defaultWikiName) != 0)
            {
                wikiPart = _wikiService.Get(_defaultWikiName);
            }

            var model = wikiPart != null ? _services.ContentManager.BuildDisplay(wikiPart) : null;

            var isEditor = _authorizationService.TryCheckAccess(StandardPermissions.AccessAdminPanel,
                            _services.WorkContext.CurrentUser,
                            null);

            return new ShapeResult(this, _services.New.Wiki_Index(
                    Name: name,
                    WikiContent: model,
                    IsEditor: isEditor
                ));
        }

        public ActionResult Questions(string name)
        {
            var wikiPart = _wikiService.Get(name);
            return new ShapeResult(this, _services.New.Wiki_Questions(
                    QuestionList: wikiPart != null ? _questionService.GetQuestionsForArticle(wikiPart.Id) : null
                ));
        }
    }
}
